<?php
namespace Home\Controller;
use Common\Library\BusinessException;
use Common\Library\Constant;
use Common\Vendor\Hook\BaseHook;
use Think\Cache\Driver\Redis;
use Think\Controller;
use Common\Library\Http\Request;
use Common\Library\Http\Response;
use Think\Log;

class IndexController extends Controller {

    public function index()
    {
        try {
            Request::parse();

            $a = I('post.ak');
            $b = I('post.bk');
            $c = I('post.ck');
            if (!$a || !$b || !$c) {
                BusinessException::throwException('请上行测试参数ak,bk,ck', 1);
            }

            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['data'] = [
                'request' => ['ak' => $a, 'bk' => $b, 'ck' => $c],
                'id' => I('post.id', 0, 'int'),
                'name' => I('post.name', '', 'string'),
                'mobile' => I('post.mobile', '', 'string'),
                'list' => [0, 1, 2, 3],
                'empty_list' => [],
                'dict' => ['hello' => 'world'],
                'empty_dict' => new \stdClass(),
                'true' => true,
                'false' => false,
                'int' => 100000,
                'string' => 'string',
                'float' => 3.45,
                'null' => null,
            ];
        } catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        $ret = Response::format($ret);
        $this->ajaxReturn($ret);
    }

    public function upload() {
        $this->display();
    }

    public function deleteBankCard() {
        try {
            $customerId = I('get.customer_id', 0, 'int');
            D('Customer')->has($customerId);

            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['affected_rows'] = M('CustomerBankInfo')->where(['customer_id' => $customerId])->delete();
        } catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        $this->ajaxReturn($ret);
    }

    public function delCustomer() {
        try {
            $customerId = I('get.customer_id', 0, 'int');
            D('Customer')->has($customerId);

            $ret = Constant::getReturn(Constant::SUCCESS);
            $ret['affected_rows'] = D('Customer')->where(['id' => $customerId])->delete();
        } catch (BusinessException $e) {
            $ret = ['code' => $e->getCode(), 'msg' => $e->getMessage()];
        }

        $this->ajaxReturn($ret);
    }

    public function phpinfo() {
        if (I('get.hello') == 'world') {
            echo phpinfo();
        }
    }

    public function redis() {
        if (ob_get_level() == 0) {
            ob_start();
        }

        $redis = new Redis();
        $redis->set('verify_code', '123456', 10);
        $i = 1;
        while (true) {
            if (($vcode = $redis->get('verify_code'))) {
                echo '验证码是:' . $vcode . ' timer:' . $i . "<br />";
                echo str_pad('',4096)."\n";
                ob_flush();
                flush();
                sleep(1);
                $i++;
                continue;
            }

            echo '验证码过期';
            break;
        }

        ob_end_flush();
    }

    public function  country()
    {
        //执行决策引擎
        $data = D("Customer")->where(['id' => 13])->find();
        $ret = BaseHook::executeHook("DECISION_ENGINE_HOOK", $data);
        Log::write("decision exception:".json_encode($ret));
        if (Constant::SUCCESS != $ret['code']) {
            BusinessException::throwException($ret['code'], $ret['msg']);
        }
    }

    public  function getProvinceName() {

        $customer = D("Customer")->where(['id'=>6])->find();
        $ret = BaseHook::executeHook("DECISION_ENGINE_HOOK", $customer);
        var_dump($ret);


        return false;
    }

    public function cleanReplicateRepayment() {
        date('md') == '0806' or die('access denied');
        // 临时清理重复分期订单数据的接口,不要运行


        // 1. 处理7.31日的脏数据
        $Model = D('ConsumeInstallmentHistory');
        $data = $Model->query("SELECT * FROM consume_installment_history ORDER BY parent_id ASC, add_time ASC");
        $bad_month = [
            '10' => '09',
            '12' => '11',
            '03' => '01',
            '05' => '04',
        ];

        $unfixed_list = [];
        foreach ($data as $_item) {
            if (date('m-d', $_item['add_time']) == '07-31') {
                $repayment_m = date('m', $_item['repayment_time']);
                $pid = $_item['parent_id'];
                if (!isset($unfixed_list[$pid])) {
                    $unfixed_list[$pid] = $bad_month;
                }

                if (isset($unfixed_list[$pid][$repayment_m])) {
                    $update = [
                        'repayment_time' => strtotime('2016-' . $unfixed_list[$pid][$repayment_m] . '-10')
                    ];

                    var_dump('parent_id:' . $pid . ' 从' . $repayment_m . ' 改为:2016-' . $unfixed_list[$pid][$repayment_m] . '-10');
                    unset($unfixed_list[$pid][$repayment_m]);
                    $Model->where(['id' => $_item['id']])->save($update);
                }
            }
        }


        // 处理重复数据
        $data = $Model->query("SELECT * FROM consume_installment_history ORDER BY parent_id ASC, add_time ASC");

        $fixed_data = $repeat_data = [];
        foreach ($data as $item) {
            $pid = $item['parent_id'];
            $repayment_time = $item['repayment_time'];
            if (!isset($fixed_data[$pid][$repayment_time])) {
                $fixed_data[$pid][$repayment_time] = $item;
            } else {
                $repeat_data[] = $item;
            }
        }

        $repeat_id_list = array_column($repeat_data, 'id');
        var_dump('发现重复分期消费记录', $repeat_id_list);
        $Model->delete(join(',', $repeat_id_list));
    }
}
